package com.five.admin.redis;

import com.five.service.CommonOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class RedisKeyExpirationListener implements MessageListener {

    private static final String ORDER_CANCEL_LM_KEY = "order:cancel";

    @Resource
    private CommonOrderService commonOrderService;
    @Override
    public void onMessage(Message message, byte[] pattern) {
        try {
            String expiredKey = message.toString();
            //拿到对应的id
            if (expiredKey.startsWith(ORDER_CANCEL_LM_KEY)) {
                String orderId = expiredKey.substring(ORDER_CANCEL_LM_KEY.length() + 1);
                //取消订单的逻辑
                cancelOrder(Long.parseLong(orderId));
                log.info("订单{}取消成功", orderId);
            }else {
                log.info("Redis键过期：{}", expiredKey);
            }
        }catch (Exception e) {
            log.error("处理Redis键过期事件失败", e);
        }
    }

    /**
     * 取消超时没有支付的订单
     * @param orderId
     */
    private void cancelOrder(Long orderId) {
        commonOrderService.cancelOrder(orderId, "超时未支付");
    }
}
